package com.msdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.msdp.dto.Result;
import com.msdp.entity.Shop;
import com.msdp.mapper.ShopMapper;
import com.msdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msdp.utils.RedisData;
import com.msdp.utils.RedisUtils;
import com.msdp.utils.SystemConstants;
import com.msdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.msdp.utils.MessageConstants.SHOP_NOT_EXIST;
import static com.msdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    private static final String UV_KEY = "uv:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private  RBloomFilter<String> bloomFilter;


    /**
     * 根据id查询商铺信息
     * @param id
     * @return
     */
    @Override
    public Result queryShopById(Long id) {
        // 布隆过滤解决缓存穿透
        boolean exists = bloomFilter.contains(id.toString());
        log.info("是否存在{}， {}", id, exists);
        if(!exists){
            return Result.fail(SHOP_NOT_EXIST);
        }
        // 1. 从Redis中查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String json = stringRedisTemplate.opsForValue().get(key);

        // 2.判断缓存是否命中
        if (StrUtil.isNotBlank(json)) {
            // 3.命中后判断是否为空
            return Result.ok(JSONUtil.toBean(json, Shop.class));
        }

        // 4.未命中->根据id查询数据库
        Shop shop = getById(id);

        // 5.判断商户是否存在
        if (shop == null) {
            // 5.1不存在->缓存null值解决缓存穿透问题
            // 5.2返回404
            return Result.fail(SHOP_NOT_EXIST);
        }

        // 6.存在->将数据写入Redis
        json = JSONUtil.toJsonStr(shop);
        saveShop2Redis(id, CACHE_SHOP_TTL, json);
        // 1. 解决缓存穿透
//        Shop shop = redisUtils
//                .queryShopByIdWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 2. 互斥锁解决缓存击穿
//        Shop shop = redisUtils.queryShopByIdMutex(id);
//         2. 逻辑过期解决缓存击穿
//        Shop shop = redisUtils
//                .queryLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
//        if (shop == null) {
//            return Result.fail(SHOP_NOT_EXIST);
//        }
        // 7.返回商铺信息
        return Result.ok(shop);
    }

    public void saveShop2Redis(Long id, Long expireSeconds, String json) {
        String key =  CACHE_SHOP_KEY + id;
        // 查询商铺信息
        Shop shop = getById(id);
//        Thread.sleep(200);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        // 设置逻辑过期时间
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 存入Redis
//        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
        stringRedisTemplate.opsForValue().set(key, json);
    }

    /**
     * 更新店铺信息
     * @param shop
     */
    @Transactional
    @Override
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail(SHOP_NOT_EXIST);
        }
        String key = CACHE_SHOP_KEY + shop.getId();
        // 更新数据库
        updateById(shop);

        // 删除缓存
        stringRedisTemplate.delete(key);

        return Result.ok();
    }

    /**
     * 查询商铺位置信息
     * @param typeId
     * @param current
     * @param x
     * @param y
     * @return
     */
    @Override
    public Result queryShopGeo(Integer typeId, Integer current, Double x, Double y) {
        // 判断是否需要根据坐标查询
        if(x == null || y == null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        // 计算分页参数
        int start = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 查询redis、按照距离排序、分页。结果：shopId， distance
        String key = SHOP_GEO_KEY + typeId;
        // 根据x y坐标查询符合要求的商户 GEOSEARCH FROMLONLAT x y BYBOX COUNT 2 WITHDIST
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );

        if(results == null){
            return Result.ok(Collections.emptyList());
        }


        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        if (content.size() <= start) {
            // 没有下一页了，结束
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>();
        Map<String, Distance> distanceMap = new HashMap<>();
        content.stream().skip(start).forEach(result -> {
            // 获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));

            // 获取店铺距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        // 根据id值查询商户
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query()
                                .in("id", ids)
                                .last("ORDER BY FIELD(id, " + idStr + ")")
                                .list();
        for (Shop shop : shops) {
            // 添加距离信息
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        // 返回数据
        return Result.ok(shops);
    }

    @Override
    public Result queryShopUV(Long id) {
        // 1. 将当前用户插入访客列表
        Long userId = UserHolder.getUser().getId();
        String key = UV_KEY + id;
        stringRedisTemplate.opsForHyperLogLog().add(key, userId.toString());
        // 2. 获取UV数量
        Long size = stringRedisTemplate.opsForHyperLogLog().size(key);
        // 3. 返回
        return Result.ok(size);
    }
}
